package com.focus.xyz.other.cases;

import com.focus.xyz.core.common.listeners.ErrorDataSplitListener;
import com.focus.xyz.core.common.webdriver.DriverFactory;
import com.focus.xyz.core.utils.*;
import com.focus.xyz.core.utils.prop.ConfigPropInfo;
import com.focus.xyz.other.pages.tpytb.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.*;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by cimon on 2016/3/30.
 */

@Listeners({ErrorDataSplitListener.class})
public class DataDrivenTest {

    private WebDriver driver;
    private String baseUrl = "http://ebiz.cpic.com.cn/lywx/";
    private String mainUrl = "http://ebiz.cpic.com.cn/lywx/html/main.jsp";


    @Parameters({"nodeUrl","browser"})
    @BeforeMethod(alwaysRun = true)
    public void setUp(String nodeUrl,String browser) throws Exception{
        driver = DriverFactory.getDriver(nodeUrl).getBrowser(browser);
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get(mainUrl);
        loginUseCookie(driver, ConfigPropInfo.TEST_DATA_DIR + "cookies/" + ConfigPropInfo.TEST_TB_LOGIN_COOKIE_FILE);
    }

    @AfterMethod(alwaysRun = true)
    public void tearDown(){
        if(driver!=null){
            driver.close();
            driver.quit();
        }
        if(ProcessUtil.findProcess("iexplore.exe")){
            ProcessUtil.killProcess("iexplore.exe");
        }
    }

    @DataProvider(name = "tbdata")
    public Object[][] getTbData(){
        String[][] data = null;
        try {
            data = ExcelUtils.getData(new File(ConfigPropInfo.TEST_DATA_DIR + ConfigPropInfo.TEST_DATA_FILE));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    @DataProvider(name = "tbdata1")
    public Object[][] getData1(){
        String[][] data = null;
        try {
            ExcelUtils eu = new ExcelUtils();
            eu = eu.RestoreSettings();//还原设定
            eu.setStartReadPos(1);
//            eu.setEndReadPos(-1);
            data = eu.readExcelArray(ConfigPropInfo.TEST_DATA_DIR + ConfigPropInfo.TEST_DATA_FILE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    @Test(dataProvider = "tbdata")
    public void autoTouBao(String prodCode,String custName,String carNo,String cardNo,String sits,String beginTime,String insFee,String com,String s9) throws Exception{
        System.out.println(prodCode+" "+custName+" "+carNo+" "+cardNo+" "+sits+" "+beginTime+" "+insFee+" "+com+" "+s9);

        allOperation(prodCode,custName,cardNo,carNo,sits,beginTime,com);
//        error(carNo);
    }

    //在cookie失效的情况下需要手动登录一次。只需要输入验证码
    public void loginUseCookie(WebDriver driver,String fileName) throws Exception{
        if(CookieUtils.addCookie(driver,fileName)){
            driver.get(mainUrl);
            driver.manage().window().maximize();
        }else{
            driver.get(mainUrl);
            driver.manage().window().maximize();
            if(driver.getPageSource().contains("系统超时，请重新登录！")){
                ReLoginPage reLoginPage = new ReLoginPage(driver);
                reLoginPage.clickRelogin();
                LoginPage loginPage = new LoginPage(driver);
                loginPage.inputUserName("WUXA145");
                loginPage.inputPassword("Cpic1234*");
                Thread.sleep(5000);
                loginPage.login();
                driver.get(mainUrl);//点登录之后要再打开一次主页
                driver.manage().window().maximize();
                CookieUtils.saveCookie(driver,fileName,".ebiz.cpic.com.cn");
            }
        }
    }

    //保单截图
    public void insScreenShot(String name,String com,String currentInsId,String appNo) throws Exception{
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        StringBuffer sb = new StringBuffer();
        sb.append(ConfigPropInfo.TEST_SRCSHOT_DIR + com + "_"+ getCurrentDay() + File.separator + name + "_" + currentInsId +"_"+appNo+ ".png");
        File destFile = new File(sb.toString());
        FileUtils.copyFile(scrFile,destFile);
    }

    public void insScreenShot1(String name,String com) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
        Capture.capture("http://ebiz.cpic.com.cn/lywx/htmlreport/05_02.jsp",
                ConfigPropInfo.TEST_SRCSHOT_DIR + com + "_"+ getCurrentDay() + File.separator + name + "_" + sdf.format(new Date(System.currentTimeMillis())) + ".png");
    }




    //根据车主名 判断证件类型  name大于4位是公司，证件类型选 其他，四位及以下是个人，证件类型选 身份证
    public String getCardTypeByCustName(String name) throws Exception{
        String type = "0";
        if (StringUtils.isBlank(name)) {
            throw new Exception("被保人为空");
        }
        int length = name.length();
        if(length>4){
            type= "4";
        }else if(length <= 4){
            type = "0";
        }else{
            throw new Exception("被保人为空");
        }
        return type;
    }

    //根据身份证号码 判断生日
    public String getBirthByCardNo(String cardNo) throws Exception{
        String birth = "1975-01-01";
        StringBuffer sb = new StringBuffer();
        if(StringUtils.isBlank(cardNo)){
            throw new Exception("证件号为空");
        }
        if (cardNo.length() == 18) {
            birth = sb.append(cardNo.substring(6,10)+"-"+cardNo.substring(10,12)+"-"+cardNo.substring(12,14)).toString();
        }else if(cardNo.length() == 15){
            birth = sb.append("19"+cardNo.substring(6,8)+"-"+cardNo.substring(8,10)+"-"+cardNo.substring(10,12)).toString();
        }
        return birth;
    }

    //根据身份证号 判断 性别
    public String getGenderByCardNo(String cardNo) throws Exception{
        String gender = "1";
        if(StringUtils.isBlank(cardNo)){
            throw new Exception("证件号为空");
        }
        if (cardNo.length() == 15 || cardNo.length() == 18) {
            String lastValue = cardNo.substring(cardNo.length() - 2, cardNo.length() - 1);
            int sex;
            if (lastValue.trim().toLowerCase().equals("x")||lastValue.trim().toLowerCase().equals("e")) {
                gender = "1";
            } else {
                sex = Integer.parseInt(lastValue) % 2;
                gender = (sex == 0 ? "2" : "1");
            }
        } else {
            gender = "1";
        }
        return gender;
    }

    public String getSitCountBySits(String sits) throws Exception{
        if(StringUtils.isBlank(sits)){
            throw new Exception("座位数为空");
        }
        return sits.substring(0,1);
    }


    public void allOperation(String prodCode,String custName,String cardNo,String carNo,String sits,String beginTime,String com) throws Exception{
        //打开主页选择投保
        MainPage mainPage = PageFactory.initElements(driver, MainPage.class);
        mainPage.clickTb();
        ProductPage productPage = PageFactory.initElements(driver,ProductPage.class);
        productPage.inputProdCode(prodCode);
        productPage.queryProd();
        productPage.selectProd();
        productPage.iwantTb();

        //切换到二层窗口
        WindowUtils.switchToWindowByUrl(driver,"ebiz.cpic.com.cn/lywx/selectproducts.do?method=insuranceProduct");
        InsDetailPage insDetailPage = PageFactory.initElements(driver,InsDetailPage.class);
        insDetailPage.openAddCustLink();

        //切换到第一层窗口
        WindowUtils.switchToWindowByUrl(driver,"ebiz.cpic.com.cn/lywx/selectproducts.do?method=init&isQuery=true");

        //切换到三层窗口
        WindowUtils.switchToWindowByUrl(driver,"ebiz.cpic.com.cn/lywx/insurance.do?method=processUnitSCX&oprate=init");
        driver.manage().window().maximize();

        //新增客户信息
        AddCustInfoPage addCustInfoPage = PageFactory.initElements(driver,AddCustInfoPage.class);
        addCustInfoPage.inputCustInfo(custName);
        String ct = getCardTypeByCustName(custName);
        addCustInfoPage.selectCardType(ct);//0--身份证；1--军官证；2--护照；3--驾驶证；4--其他
        //如果证件类型是身份证 则根据身份证判断 生日及性别，如不是 则给默认值
        if("0".equals(ct)){
            addCustInfoPage.selectGender(getGenderByCardNo(cardNo));//1--男；2--女；3--不详
        }else{
            addCustInfoPage.selectGender("1");
        }
        addCustInfoPage.inputCustCardNo(cardNo);
        if("0".equals(ct)){
            addCustInfoPage.inputBirthDate(getBirthByCardNo(cardNo));
        }else{
            addCustInfoPage.inputBirthDate("1975-01-01");
        }
        addCustInfoPage.clickAdd();
        //如果录入客户信息失败，再重新录入一遍
        if(WindowUtils.isAlertPresent(driver)){
            driver.switchTo().alert().accept();
            addCustInfoPage.inputCustInfo(custName);
            addCustInfoPage.selectCardType(ct);
            if("1".equals(getGenderByCardNo(cardNo))){
                addCustInfoPage.selectGender("2");
            }else if("2".equals(getGenderByCardNo(cardNo))){
                addCustInfoPage.selectGender("1");
            }
            addCustInfoPage.inputCustCardNo(cardNo);
            if("0".equals(ct)){
                addCustInfoPage.inputBirthDate(getBirthByCardNo(cardNo));
            }else{
                addCustInfoPage.inputBirthDate("1975-01-01");
            }
            addCustInfoPage.clickAdd();
        }
        addCustInfoPage.clickCustRow();
        addCustInfoPage.clickConfirmBtn();

        //切换到二层窗口
        WindowUtils.switchToParentWindow(driver,"ebiz.cpic.com.cn/lywx/selectproducts.do?method=insuranceProduct");

        //-----获取当前的投保单ID。
        String currentInsIdNo = insDetailPage.getInsNoId();
        insDetailPage.inputInsBeginTime(beginTime);
        insDetailPage.inputCarNo(carNo);
        insDetailPage.inputSits(getSitCountBySits(sits));
        insDetailPage.selectCarInfo();
        insDetailPage.finish();
        Thread.sleep(2000);
        Assert.assertFalse(driver.getPageSource().contains("投保失败"));//----当保单ID被占用的时候会提示，此时应按失败处理
        //取保险单ID
        String appNoId = "";
        try{
            WebElement appNo = driver.findElement(By.xpath("//body/div[1]/font"));
            String tmp = appNo.getText();
            if(StringUtils.isNotBlank(tmp)){
                appNoId = tmp.split("：")[1].trim();
            }
        }catch (NoSuchElementException e){

        }
        driver.get("http://ebiz.cpic.com.cn/lywx/htmlreport/05_02.jsp");
        if(driver.getPageSource().contains(currentInsIdNo)){
            insScreenShot(carNo,com,currentInsIdNo,appNoId);
        }else{
            logScrError(carNo,currentInsIdNo,com);
        }
    }

    public void logScrError(String carNo,String currentInsIdNo,String com) throws Exception{
        String[] ss = new String[]{carNo,currentInsIdNo,"截图错误"};
        ResourceUtil.appendFileContent(ConfigPropInfo.TEST_SRCSHOT_DIR + com + "_" +
                getCurrentDay() + ".txt",ss);
    }

    public String getCurrentDay() throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date(System.currentTimeMillis()));
    }

    public void error(String carNo) throws Exception{
        Assert.fail();
//        throw new Exception("eeeeeeeeeeee");
    }
}
